package com.ms.jsf.util;

import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

public class ViewExpiredExceptionExceptionHandler extends ExceptionHandlerWrapper {
    private ExceptionHandler wrapped;

    public ViewExpiredExceptionExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public ExceptionHandler getWrapped() {
        return this.wrapped;
    }

    @Override
    public void handle() throws FacesException {
        for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
            ExceptionQueuedEvent event = i.next();
            ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
            Throwable t = context.getException();
            if (t instanceof ViewExpiredException) {
                ViewExpiredException vee = (ViewExpiredException) t;
                FacesContext facesContext = FacesContext.getCurrentInstance();
                Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
                try {
                    // Push some useful stuff to the request scope for use in the page
                    requestMap.put("currentViewId", vee.getViewId());
                    String url = null;
                    try {
                        url = generateUrl((HttpServletRequest) facesContext.getExternalContext().getRequest());
                    } catch (IOException e) {
                        throw new FacesException(e);
                    }
                    if (url == null) {
                        NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
                        navigationHandler.handleNavigation(facesContext, null, "/viewExpired");
                    } else {
                        try {
                            facesContext.getExternalContext().redirect(url);
                        } catch (IOException e) {
                            throw new FacesException(e);
                        }
                    }
                    facesContext.renderResponse();
                } finally {
                    i.remove();
                }
            }
        }

        // At this point, the queue will not contain any ViewExpiredEvents. Therefore, let the parent handle them.
        getWrapped().handle();
    }

    private String generateUrl(HttpServletRequest request) throws IOException {
        String url = null;
        String loginUrl = request.getRequestURL().toString();
        if (loginUrl.indexOf("login") != -1) {
            String usuario = "";
            String password = "";
            String pais = "";
            String portal = "";
            // url=  loginUrl;
            url = request.getContextPath() + "/j_spring_security_check";
            if (request.getParameter("j_username") != null) {
                usuario = request.getParameter("j_username");
            }
            if (request.getParameter("j_password") != null) {
                password = request.getParameter("j_password");
            }
            if (request.getParameter("j_pais_input") != null) {
                pais = request.getParameter("j_pais_input");
            }
            if (request.getParameter("j_portal") != null) {
                portal = request.getParameter("j_portal");
            }
//            portal = UtilResource.getApplicationId();
            url = url + "?j_username=" + usuario + "&j_password=" + password + "&j_pais_input=" + pais + "&j_portal=" + portal;
        }
        return url;
    }
}
